package giftmail.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import giftmail.annotation.SystemLog;
import giftmail.model.User;
import giftmail.service.ILoginService;
import giftmail.staticentity.SessionInfo;

@Controller
@RequestMapping(value = "/loginController")
public class LoginController {

	@Autowired
	private ILoginService loginService;
	
	/**
	 * 跳转到登录页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/toLogin")
	public String toLogin() {
		return "/login";	//跳转到login.jsp  ==>  如果使用了freemarker则跳转到login.ftl
	}

	/**
	 * 登录操作
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login")
	@SystemLog(funname = "用户登录", memo="登录操作")
	public String login(HttpServletRequest request,ModelMap model) {
		HttpSession session = request.getSession();
		
		String userName = request.getParameter("userName");
		String userPwd = request.getParameter("userPwd");

		// 校验用户名和密码不能为空
		if (userName == null || userPwd == null) {
			model.put("message", "用户名或密码不能为空");
			return "redirect:/loginController/toLogin";	//转发
		}else{
			User user = loginService.login(userName, userPwd);
			if (user == null) {
				model.put("message", "用户名或密码错误");
				return "redirect:/loginController/toLogin";	//转发
			}else{
				// 登录用户存放到session
				session.setAttribute(SessionInfo.SESSION_LOGIN_USER, user);
			}
		}
		return  "forward:/loginController/index";	//跳转到/index方法中
	}
	
	/**
	 * 进入后台主界面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request, ModelMap model) {
		//检查session是否已经登录
		HttpSession session = request.getSession();
		User sysUser = null;
		if (session.getAttribute(SessionInfo.SESSION_LOGIN_USER) != null) {
			sysUser = (User)session.getAttribute(SessionInfo.SESSION_LOGIN_USER);
		} else {
			return "redirect:/toLogin";	//跳转到/toLogin方法中
		}
		model.put("sysUser", sysUser);
		
		return "/index";	//页面index.jsp  ==>  如果使用了freemarker则跳转到index.ftl
	}
	
	
}
